package com.firewolf.hibernate.main;

import java.util.Date;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;
import org.hibernate.service.ServiceRegistryBuilder;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;

import com.firewolf.hibernate.dto.News;

/***
 * 由于这里默认就是事务的，所以在commit之前，是不会修改数据库的数据的
 * @Description:
 * @Author: 刘兴
 * @Date : 2016年10月21日
 * @package : com.firewolf.hibernate.main
 * @Java_Version : 1.7
 * @Version : 2016年10月21日下午1:36:25
 */
public class MainDriver {

	private SessionFactory factory = null;
	
	private Session session = null;
	
	private Transaction transaction;

	@Before
	public void init() {
		Configuration cfg = new Configuration().configure();

		ServiceRegistry registry = new ServiceRegistryBuilder().applySettings(cfg.getProperties())
				.buildServiceRegistry();
		factory = cfg.buildSessionFactory(registry);
	}

	@After
	public void destory() {
		factory.close();
	}

	
	private void openSession(){
		session = factory.openSession();
		transaction = session.beginTransaction();
	}
	
	private void closeSession(){
		transaction.commit();
		session.close();
	}
	@Test
	public void save() {
		openSession();

		News news = new News("十堰新闻ccc", "武松", new Date());
		session.save(news);
		
		
		closeSession();
	}
	
}
